<template>
    <pageTabelLayout>
        <template #pageHeader>
            <!-- <div class="search-form" v-if="headerShow">
                  <a-form size="small" :model="pageData" layout="inline">
                      <a-form-item label="补扣类型">
                          <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                              v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                              @focus="focusSel">
                              <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                          </a-select>
                      </a-form-item>
                  </a-form>
              </div>
              <div class="my-divisders">
                  <a-divider orientation="center">
                      <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                      <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                  </a-divider>
              </div> -->
            <div class="my-tool-bar">
                <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @excel="downloadHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <!-- <a-tabs   :justify="true">
                  <a-tab-pane> -->
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef" class="ag-theme-alpine"
                :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
            <paginationCopys :total="total" show-total show-jumper show-page-size :page-size="pagination.pageSize"
                :current="pagination.page" @change="PageSize" @page-size-change="change1" style="justify-content: center" />
            <!-- </a-tab-pane>
              </a-tabs> -->
        </template>

        <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="80px" label="乐捐类型" field="typeName" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '乐捐类型必填' }]">
                        <a-input class="bacClass" placeholder="" v-model="dataForm.typeName" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="计算方式" field="typeMode" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '计算方式必填' }]">
                        <a-select popup-container="html" v-model="dataForm.typeMode" placeholder="" class="bacClass">
                            <a-option>-</a-option>
                            <a-option>+</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="备注">
                        <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                            show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>
  
<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { AnyARecord } from 'dns'

import { localeText } from '@/api/aggridZw'
interface BrandInfo {
    id: any
    remark: string | undefined
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    deleteState: any
    obsoleteState: any
    serial: any
    typeName: any
    typeMode: any
    unit: any
}

export default {
    name: 'SettingsForDonationTypes',
    setup() {
        const total = ref(10)
        const page = ref(1)
        const size = ref(10)
        function PageSize(val: any) {
            pagination.page = val
            doRefresh()
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh()
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {
            pageData.pageLoading = true
            post({
                url: '/pieceData/fillDeductType/getPage',
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: '0',
                    // typeName: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.data)
                        gridOption.value.setRowData(data.data)
                        total.value = data.total
                    }
                })
                .catch(console.log)
                .finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection()
        const pagination = usePagination(doRefresh)
        const table = useTable()
        const rowKey = useRowKey('id')
        const tableColumns = useTableColumn([
            {
                title: '序号',
                key: 'serialNumber',
                dataIndex: 'serialNumber',
                width: 150,
            },
            {
                title: '乐捐类型',
                key: 'typeName',
                dataIndex: 'typeName',
                width: 150,
            },
            {
                title: '计算方式',
                key: 'typeMode',
                dataIndex: 'typeMode',
                width: 150,
                slotName: 'typeMode',
            },
            {
                title: '备注',
                key: 'remark',
                dataIndex: 'remark',
                width: 150,
            },
            {
                title: '创建人',
                key: 'createName',
                dataIndex: 'createName',
                width: 150,
            },
            {
                title: '创建时间',
                key: 'createTime',
                dataIndex: 'createTime',
                width: 200,
            },
            {
                title: '最后修改人',
                key: 'updateName',
                dataIndex: 'updateName',
                width: 150,
            },
            {
                title: '最后修改时间',
                key: 'updateTime',
                dataIndex: 'updateTime',
                width: 200,
            },
            {
                title: '操作',
                key: 'id',
                slotName: 'act',
                width: 150,
                fixed: 'right',
            },
        ])
        let tc: any[] = tableColumns.map((o) => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed'],
                tooltipField: o.key,
            }
            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj['lockPosition'] = 'right'
                obj['width'] = '80px'
                obj['cellRenderer'] = {
                    // template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
                    template: `<el-button style="color:#165dff;" v-if="isEdit" type="info" link @click="a">修改</el-button>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        let isEdit = permissionStore.hasPermisson('kblx.xg')
                        return {
                            a,
                            isEdit,
                        }
                    },
                }
            }
            return obj
        })

        let a = [
            {
                showRowGroup: 'hide_def',
                headerName: '',
                checkboxSelection: true,
                headerCheckboxSelection: true,
                pinned: 'left',
                width: 50,
                resizable: false,
                filter: false,
                sortable: false,
                minWidth: 50,
                maxWidth: 50,
                lockPosition: 'left',
            },
        ]
        tc = a.concat(tc)

        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            nameList: []
            pageLoading: boolean
            typeList: []
            dropDownData1: any
            rHeight: any
            btnList: any[]
            isEdit: boolean
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增乐捐类型基础资料',
            dropDownData: '',
            pageLoading: false,
            typeList: [],
            dropDownData1: '',
            rHeight: 0,
            btnList: [],
            isEdit: false,
        })

        interface gcType {
            id: any
            company: any
        }
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ typeName: '', deleteState: 0 })
        }

        //下拉数据
        const options = ref<any>(pageData.nameList)
        const loading = ref(false)
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { typeName: value, deleteState: 0 }
                loading.value = true
                selCxAll(ob)
                options.value = pageData.nameList
                loading.value = false
            } else {
                options.value = []
            }
        }
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: '/pieceData/fillDeductType/getFieldValue',
                data: val,
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data)
                    let dataList: any = []
                    data.forEach(function (o: any) {
                        dataList.push(o['typeName'])
                    })
                    pageData.nameList = dataList
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
        }

        onMounted(() => {
            // 切换tap到本页面执行的方法
            emitter.on('BuckleType', () => {
                doRefresh()
            })
        })

        let cxbl = {}
        //查询
        const selectHandler = () => {
            pagination.page = 1
            cxbl = pageData.dropDownData
            doRefresh()
        }
        const queryData = reactive({
            typeName: '',
        })
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === 'id') {
                    dataForm[key] = null
                } else {
                    dataForm[key] = ''
                }
            }
            pageData.showAdd = true
            pageData.sideTitle = '新增乐捐类型基础资料'
        }
        const dataForm = reactive<BrandInfo>({
            id: null,
            remark: '',
            createName: '',
            createTime: '',
            updateName: '',
            updateTime: '',
            deleteState: 0,
            obsoleteState: '',
            serial: 0,
            typeName: '',
            typeMode: '',
            unit: '',
        })

        // 表格准备事件
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    formRef.value?.validate().then((err) => {
                        if (!err) {
                            pageData.pageLoading = true
                            if (pageData.sideTitle === '新增乐捐类型基础资料') {
                                post({
                                    url: '/pieceData/fillDeductType/insert',
                                    data: [dataForm],
                                })
                                    .then((res: any) => {
                                        if (res.code === 200) {
                                            formRef.value?.resetFields()
                                            pageData.showAdd = false
                                            Message.success({
                                                content: '新增成功',
                                                duration: 5000,
                                            })
                                        } else {
                                            Message.error({
                                                content: res.message,
                                                duration: 5000,
                                            })
                                        }
                                        doRefresh()
                                    })
                                    .finally(() => {
                                        doRefresh()
                                        pageData.pageLoading = false
                                    })
                            } else {
                                post({
                                    url: '/pieceData/fillDeductType/update',
                                    data: [dataForm],
                                })
                                    .then((res: any) => {
                                        if (res.code === 200) {
                                            formRef.value?.resetFields()
                                            pageData.showAdd = false
                                            Message.success({
                                                content: '修改成功',
                                                duration: 5000,
                                            })
                                        } else {
                                            Message.error({
                                                content: res.message,
                                                duration: 5000,
                                            })
                                        }
                                        //doRefresh();
                                    })
                                    .finally(() => {
                                        doRefresh()
                                        pageData.pageLoading = false
                                    })
                            }
                        }
                    })
                }
            })
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true
                    post({
                        url: '/pieceData/fillDeductType/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => {
                            return o.id
                        }),
                    })
                        .then(({ code, data }: any) => {
                            if (code === 200) {
                                Message.success({
                                    content: '删除成功',
                                    duration: 5000,
                                })
                                pagination.page = 1
                                doRefresh()
                            } else {
                                Message.error({
                                    content: '修改失败',
                                    duration: 5000,
                                })
                            }
                        })
                        .finally(() => {
                            pageData.pageLoading = false
                        })
                },
            })
        }
        const editHandler = (record: BrandInfo) => {
            //循环对象 赋值
            for (let key in record) {
                dataForm[key] = record[key]
            }
            // if (dataForm.typeMode == 0) {
            //     dataForm.typeMode = '-'
            // } else {
            //     dataForm.typeMode = '+'
            // }
            pageData.sideTitle = '修改乐捐类型基础资料'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>((resolve) => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            dataForm.unit = dataForm.unit.toUpperCase()
        }
        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['id'])
                })
                //将表头拼接出来
                let head =
                    '<th>序号</th><th>乐捐类型</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return (
                        gridOption.value
                            .getSelectedRows()
                            .map((o: any) => {
                                return o.id
                            })
                            .indexOf(o['id']) !== -1
                    )
                })
                let body = ''
                nowRow.forEach(function (o) {
                    body += '<tr><td>' + o['id'] + '</td>'
                    body += '<td>' + o['typeName'] + '</td>'
                    body += '<td>' + o['remark'] + '</td>'
                    body += '<td>' + o['createName'] + '</td>'
                    body += '<td>' + o['createTime'] + '</td>'
                    body += '<td>' + o['updateName'] + '</td>'
                    body += '<td>' + o['updateTime'] + '</td>'
                    body += '</tr>'
                })
                tableToXlsx(head, '乐捐类型', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
              <head><meta charset="UTF-8"></head>
              <body><table border="1"><tr>${head}</tr>${body}</table></body>
          </html>`

            const a = document.createElement('a')
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
            a.download = filename
            a.click()
            document.removeChild(a)
        }

        //模板下载
        const downloadHandler = () => {
            axios
                .get(baseURL + '/pdm/transportName/uploadModel', {
                    responseType: 'blob',
                    headers: {
                        token: sessionStorage.getItem('USER-TOKEN-KEY'),
                    },
                })
                .then((res) => {
                    if (res.status === 200) {
                        filedownload(res.data, '乐捐类型.xlsx')
                    }
                })
        }
        //导入
        const importHandler = () => {
            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept =
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！')
                    return
                }
                pageData.pageLoading = true
                axios
                    .post(baseURL + '/pdm/transportName/importModelData', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            token: sessionStorage.getItem('USER-TOKEN-KEY'),
                        },
                    })
                    .then((result) => {
                        if (result.data['code'] === 200) {
                            Message.success('导入成功')
                        } else {
                            Message.error(result.data.message)
                        }
                    })
                    .finally(() => {
                        pageData.pageLoading = false
                        doRefresh()
                    })
            })
            inputEle.click()
        }
        //下拉数据
        const options1 = ref<any>(pageData.nameList)
        const loading1 = ref(false)
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = {
                    key: value,
                    deleteState: 0,
                }
                loading.value = true
                selCxAll1(ob)
                options.value = pageData.nameList
                loading.value = false
            } else {
                options.value = []
            }
        }
        //下拉框查询
        function selCxAll1(val: any) {
            post({
                url: '/pdm/transportName/getFieldValue',
                data: val,
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.nameList = data
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ key: '' })
        }
        const handleChange = (_data: any) => {
            table.handleSuccess(_data)
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        const localeText1: any = ref(localeText)
        // :items="['查询', '新增', '删除']"
        const permissionStore = usePermission()
        if (permissionStore.hasPermisson('kblx.cx')) {
            pageData.btnList.push('查询')
        }
        if (permissionStore.hasPermisson('kblx.xz')) {
            pageData.btnList.push('新增')
        }
        if (permissionStore.hasPermisson('kblx.sc')) {
            pageData.btnList.push('删除')
        }
        return {
            localeText1,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            inputBlur,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            downloadHandler,
            importHandler,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            page,
            size,
        }
    },
    components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

.toolbar-item {
    cursor: pointer;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
    text-align: center;
}
</style>